package kayao.common;

import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Date;

public class Client {
	private String name = "";
	private int id;
	private String ip;
	private int team;
	private long loginTime;
	
	public Client(String name,int ID, String IP, int TEAM){
		this.name=name;
		this.id = ID;
		this.ip = IP;
		this.team = TEAM;
		this.loginTime = System.currentTimeMillis();
	}

	public void setName(String name){
		this.name = name;
	}
	public void setId(int id){
		this.id = id;
	}

	public void setIP(String IP){
		this.ip = IP;
	}
	public void setTeam(int team){
		this.team = team;
	}

	public String getName(){
		return this.name;
	}
	public int getId(){
		return this.id;
	}

	public String getIP(){
		return this.ip;
	}
	public int getTeam(){
		return this.team;
	}
	
	public String toString(){
		String str = name+"\t"+id+"\t"+ip+"\t\t"+convertUptime(System.currentTimeMillis()-loginTime)+"\t"+team;
		return str;
	}
	
    public String convertUptime(long uptime) {
		String format = String.format("%%0%dd", 2);
		uptime = uptime / 1000;
		String seconds = String.format(format, uptime % 60);
		String minutes = String.format(format, (uptime % 3600) / 60);
		String hours = String.format(format, uptime / 3600);
		String time =  hours + ":" + minutes + ":" + seconds;
    	return time;  
    }
	
	/**
	 * It answers a byte array with all the information needed. 
	 * The first position is the size of that information.
	 * Then the total of bytes that we return is 1+ content of the first position.
	 * @return The bytes described above. 
	 */
	public byte [] getBytes()
	{
		//size
		int size=4+4+1+getName().length();
		byte []bytes=new byte[size+1];
		byte []value=new byte[4];
		int index=1;

		//first position is the size of the rest of the array
		bytes[0]=(byte)size;
		
		//4 bytes for the id
		value=NetworkUtils.int32ToByte(getId());
		System.arraycopy(value, 0, bytes, index, 4);
		index+=4;

		//Now 4 bytes for the ips 
		InetAddress add;
		try {
			add = InetAddress.getByName(getIP());
			value=add.getAddress();
			System.arraycopy(value, 0, bytes, index, 4);
			index+=4;
		} catch (UnknownHostException e) {
			System.out.println("Error in Client: getBytes(): Unknown IP ");
		}
		
		//The name
		int length=getName().length();
		bytes[index]=(byte)length;
		index++;
		for (int j = 0; j < length; j++) {
			bytes[index] = (byte)getName().charAt(j);
			index++;
		}

		
		return bytes;
	}
}